// ===========================================
// Simple effect to texture the given object
// ===========================================

float4x4 World;
float4x4 gWVP;
texture gTex;
float4 DiffuseColor = float4(1,1,1,1);
float4 AmbientLightColor = float4(0.1,0.1,0.1,1);
bool TextureEnabled = false;
float3 LightDirection = float3(1,1,1);
float4 LightColor = float4(0.9,0.9,0.9,1);
float SpecularPower = 32;
float4 SpecularColor = float4(1,1,1,1);
float3 CameraPosition;

sampler TexS = sampler_state {
	Texture = <gTex>;
	MinFilter = ANISOTROPIC;
	MagFilter = ANISOTROPIC;
	MipFilter = LINEAR;
	AddressU  = WRAP;
    AddressV  = WRAP;
};

struct OutputVS {
    float4 posH   : POSITION0;
	float2 tex0   : TEXCOORD0;
	float3 Normal : TEXCOORD1;
	float3 ViewDirection : TEXCOORD2;
};


OutputVS TextureVS(float3 posL : POSITION0, float3 normL : POSITION1, float2 tex0: TEXCOORD0) {
    // Zero out our output.
	OutputVS outVS = (OutputVS)0;	
	// Transform to homogeneous clip space.
	outVS.posH = mul(float4(posL, 1.0f), gWVP);		
	outVS.tex0 = tex0; 
	outVS.Normal = mul(normL,World);
	outVS.ViewDirection = posL - CameraPosition;
    return outVS;
}

float4 PixelShaderFunction(OutputVS input) : COLOR {    
	float3 color = DiffuseColor.rgb;
	float alpha = DiffuseColor.a;
	if ( TextureEnabled ) {
		float4 tmp = tex2D(TexS, input.tex0);
		color *= tmp.rgb;
		alpha = tmp.a;
	}
	float3 lightning = AmbientLightColor.rgb;
	float3 lightDir = normalize(LightDirection);
	float3 normal = normalize(input.Normal);
	
	lightning += saturate(dot(lightDir,normal)) * LightColor.rgb;
	
	float3 refl = reflect(lightDir,normal);
	float3 view = normalize(input.ViewDirection);
	
	lightning += pow(saturate(dot(refl,view)),SpecularPower) * SpecularColor.rgb;
	
	float3 output = saturate(lightning) * color;
	return float4(output,alpha);
}

technique BasicTechnique {
    pass P0 {
        vertexShader = compile vs_2_0 TextureVS();
        pixelShader  = compile ps_2_0 PixelShaderFunction();
    }
}
